﻿using System;
using System.IO;
using System.Web.Mvc;
using System.Web.Http;
using System.Reflection;
using Autofac;
using Autofac.Integration.Mvc;
using Autofac.Integration.WebApi;
using Freedom.SimpleFramework.Filter;
using log4net;

namespace Freedom.SimpleFramework
{
    public abstract class AutofacApplication : System.Web.HttpApplication
    {
        private static readonly ILog Log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);

        protected virtual string ApplicationName
        {
            get { return Assembly.GetExecutingAssembly().FullName; }
        }

        protected void Application_Start()
        {
            InitLog4Net();
            InitIoC();
            //register the filters
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            OnApplicationStarted();
        }

        protected void Application_Error(object sender, EventArgs e)
        {
           Log.Debug(Server.GetLastError().Message);
        }

        protected virtual IContainer CreateContainer()
        {
            var builder = new ContainerBuilder();
            RegisterControllers(builder);
            RegisterApiControllers(builder);
            RegisterServices(builder);
            RegisterRepository(builder);
            return builder.Build();
        }

        protected virtual void OnApplicationStarted() { }

        protected virtual void RegisterControllers(ContainerBuilder builder)
        {
            builder.RegisterControllers(Assembly.GetExecutingAssembly());
        }

        protected virtual void RegisterApiControllers(ContainerBuilder builder)
        {
            builder.RegisterApiControllers(Assembly.GetExecutingAssembly());
        }

        #region abstract method
        protected abstract void RegisterServices(ContainerBuilder builder);
        protected abstract void RegisterRepository(ContainerBuilder builder);
        #endregion

        #region private methods
        private void InitIoC()
        {
            var container = CreateContainer();
            //for controller:use the autofac dependency resolver
            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
            //for api controller: use the autofac dependency resolver
            GlobalConfiguration.Configuration.DependencyResolver = new AutofacWebApiDependencyResolver(container);
        }

        private void InitLog4Net()
        {
            //config the log4net
            log4net.Config.XmlConfigurator.Configure();

            var logDirectoryPath = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + string.Format("\\{0}\\log", ApplicationName);
            if (!Directory.Exists(logDirectoryPath))
            {
                // Try to create the directory.
                Directory.CreateDirectory(logDirectoryPath);
            }

            Environment.SetEnvironmentVariable("APPLOGS", logDirectoryPath);
            // --- End Set Log Directory ---

            // --- log System Info ---
            if (Log.IsDebugEnabled)
            {
                Log.Debug("Is64BitOperatingSystem: " + Environment.Is64BitOperatingSystem);
                Log.Debug("Is64BitProcess: " + Environment.Is64BitProcess);
                Log.Debug(Environment.MachineName);
                Log.Debug(Environment.OSVersion);
                Log.Debug(Environment.UserDomainName);
                Log.Debug(Environment.UserName);
            }
            // --- End log System Info ---
        }
        #endregion
    }
}
